package tools

type ErrCatcher struct {
	Err    error
	Strict bool
}

func NewErrCatcher() *ErrCatcher {
	e := new(ErrCatcher)
	return e
}

func (e *ErrCatcher) Clear() {
	e.Err = nil
}

func (e *ErrCatcher) ClearIf(pred func(error) bool) {
	if pred(e.Err) {
		e.Clear()
	}
}

func (e *ErrCatcher) ClearIfEqual(err error) {
	if err == e.Err {
		e.Clear()
	}
}

func (e *ErrCatcher) Push(err error) error {
	return e.Execute(func() error { return err })
}

func (e *ErrCatcher) Execute(f func() error) error {
	if e.Strict && e.Err != nil {
		return e.Err
	}
	err := f()
	if e.Err == nil {
		e.Err = err
	}
	return e.Err
}
